<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!--专病数据-->
      <el-form
        class="formBox formBox1"
        :model="libraryQueryParams"
        ref="libraryQueryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item label="医院" prop="hospital" clearable>
          <department
            :isHospital="true"
            :isdepat="true"
            @refreshData="refreshData"
            deptWidth="200px"
            ref="department"
          >
          </department>
        </el-form-item>
        <el-form-item label="标注库名" prop="researchLibrariesName">
          <el-input
            v-model="libraryQueryParams.researchLibrariesName"
            placeholder="标注库名"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="负责人" prop="projectLeaders">
          <el-select
            v-model="libraryQueryParams.projectLeaders"
            placeholder="负责人"
            clearable
            filterable
            style="width: 160px"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="创建人" prop="createBy">
          <el-select
            v-model="libraryQueryParams.createBy"
            placeholder="创建人"
            clearable
            filterable
            style="width: 160px"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getLibraryList"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetLibraryQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="formBox">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="newAdd"
              >新增</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getLibraryList"
          ></right-toolbar>
        </el-row>
        <el-table border v-loading="loading" :data="annotateLibraryList">
          <!--                <el-table-column type="selection" width="50" align="center" />-->
          <el-table-column
            sortable
            label="序号"
            align="center"
            type="index"
            width="50"
          >
            <template slot-scope="scope">
              <span>{{ getIndex(scope.$index) }}</span>
            </template>
          </el-table-column>

          <el-table-column
            sortable
            label="标注库名"
            align="center"
            prop="researchLibrariesName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="医院"
            align="center"
            prop="hospitalName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <departTag
                :options="deptNameLists"
                :value="scope.row.hospitalId"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="科室"
            align="center"
            prop="deptName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <departTag :options="deptNameLists" :value="scope.row.deptId" />
            </template>
          </el-table-column>
          <el-table-column
            sortable
            label="标注医生"
            align="center"
            prop="nickNames"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            sortable
            label="创建人"
            align="center"
            prop="createBy"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            sortable
            label="创建时间"
            align="center"
            prop="createTime"
            :show-overflow-tooltip="true"
          >
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="260"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="isHaveEditPermission(scope.row)"
                @click="btnEditLibrary(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                :disabled="isHaveEditPermission(scope.row)"
                @click="btnDeleteLibrary(scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-folder"
                :disabled="isHaveOperationPermission(scope.row)"
                @click="btnListLibrary(scope.row)"
                >标注集</el-button
              >

              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                :disabled="isHaveOperationPermission(scope.row)"
                @click="btnOutAddToLibrary(scope.row)"
                >外部照片</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                :disabled="isHaveOperationPermission(scope.row)"
                @click="btnAddToLibrary(scope.row)"
                >库中选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="libraryTotal > 0"
          :total="libraryTotal"
          :page.sync="libraryQueryParams.pageNum"
          :limit.sync="libraryQueryParams.pageSize"
          @pagination="getLibraryList"
        />
      </div>
    </el-row>
    <el-dialog
      :title="libraryTitle"
      :visible.sync="libraryDialogVisible"
      width="50%"
      center
      :close-on-click-modal="false"
      :append-to-body="true"
      v-dialogDrag
    >
      <el-form
        class="formBox formBox1"
        :model="submitLibraryForm"
        ref="submitLibraryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
        :rules="submitLibraryFormRules"
      >
        <el-form-item label="科室" prop="deptId">
          <treeselect
            :defaultExpandLevel="Infinity"
            v-model="submitLibraryForm.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择科室"
            style="width: 202px"
            :disable-branch-nodes="true"
          />
        </el-form-item>
        <el-form-item label="标注库名" prop="researchLibrariesName">
          <el-input
            v-model="submitLibraryForm.researchLibrariesName"
            placeholder="标注库名"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="标注医生" prop="projectLeaders">
          <el-select
            v-model="submitLibraryForm.projectLeaders"
            placeholder="标注医生"
            clearable
            filterable
            multiple
            style="width: 475px"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="libraryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="btnSubmitLibraryForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="标注集"
      :visible.sync="annotationListDialogVisible"
      width="100%"
      center
      :close-on-click-modal="false"
      :append-to-body="true"
      v-dialogDrag
    >
      <AnnotationList v-if="annotationListDialogVisible" :libraryId="libraryId">
      </AnnotationList>
    </el-dialog>
    <el-dialog
      title="图片入库"
      :visible.sync="photosLibraryDialogVisible"
      width="100%"
      center
      :close-on-click-modal="false"
      :append-to-body="true"
      v-dialogDrag
    >
      <PhotosLibrary
        @addLibraryPindex="addLibraryPindex"
        @oneClickJoinAllPhoto="oneClickJoinAllPhoto"
        v-if="photosLibraryDialogVisible"
      >
      </PhotosLibrary>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog
      title="上传照片"
      :visible.sync="uploadPhotoDialogVisible"
      width="1280px"
      append-to-body
      :close-on-click-modal="false"
      v-dialogDrag
    >
      <photoUpload :isMorePic="false" :patientItem="patientItem"></photoUpload>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  listLibrary,
  addlibrary,
  deleteLibrary,
  getLibrary,
  updatelibrary,
  photoAddtoLibrary,
  allPhotoAddtoLibrary,
} from "@/api/system/annotationLibrary";

import { listDept, deptNameList } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { listAnnotate, delAnnotate } from "@/api/system/annotate";
import { listClassify } from "@/api/system/classify";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import photoUpload from "@/views/tagManage/components/photoUpload.vue";
import PhotoMark from "@/views/components/photoMark/photoMark.vue";
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import PhotosLibrary from "../components/photosLibrary.vue";
import AnnotationList from "../components/annotationList.vue";
export default {
  name: "annotateManage",
  dicts: [
    "sys_manage_diseases",
    "photo_upload_type",
    "photo_lighting_type",
    "sys_face_part",
    "sys_diagnosis_status",
  ],
  components: {
    Treeselect,
    photoUpload,
    PhotoMark,
    department,
    departTag,
    PhotosLibrary,
    AnnotationList,
  },
  data() {
    return {
      nickName: this.$store.state.user.nickName,
      libraryId: 0,
      libraryQueryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        deptId: undefined,
        researchLibrariesName: undefined,
        projectLeaders: undefined,
        createBy: undefined,
      },
      libraryTitle: "",
      libraryDialogVisible: false,
      submitLibraryForm: {
        hospitalId: undefined,
        deptId: undefined,
        researchLibrariesName: undefined,
        projectLeaders: undefined,
      },
      submitLibraryFormRules: {
        deptId: [{ required: true, message: "请选择科室", trigger: "blur" }],
        researchLibrariesName: [
          { required: true, message: "请输入标注库名称", trigger: "blur" },
        ],
        projectLeaders: [
          { required: true, message: "请选择标注库负责人", trigger: "blur" },
        ],
      },
      // 科室树选项
      deptOptions: undefined,
      deptOptionsArr: [],
      annotateLibraryList: [],
      libraryTotal: 0,
      deptNameLists: [],
      photosLibraryDialogVisible: false,
      annotationListDialogVisible: false,

      printDialogVisible: false,
      sysUseTypeArr: [
        { label: "未标注", value: 0 },
        { label: "已标注", value: 1 },
        { label: "已审核", value: 2 },
      ],
      editor: null,
      // 遮罩层
      loading: true,
      printInfo: {},
      // 选中数组
      ids: [],
      diseaseClassifyName: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标注表格数据
      annotateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 是否修改
      inputDisabled: false,
      // 表单参数
      // form: {},
      form: {
        title: "", //文本标题
        colorValue: "", //颜色值
        diseaseIds: "", //专病类型 （字典管理）
        label: "",
      },
      detectionType: [], //可选的 检测指标  （接口返回）仅前端用
      sysManageDiseases: [], //专病管理

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagSettingName: undefined, //标注设置名称
        diseaseId: undefined, //专病类别
        publisher: undefined, //创建人
      },
      // 表单校验
      rules: {
        title: [
          {
            required: true,
            message: "标注设置名称不能为空",
            trigger: "blur",
          },
        ],
        diseaseIds: [
          {
            required: true,
            message: "专病必选",
            trigger: "blur",
          },
        ],
        label: [
          {
            required: true,
            message: "特征名称不能为空！",
            trigger: "blur",
          },
        ],
        colorValue: [
          {
            required: true,
            message: "颜色值不能为空！",
            trigger: "blur",
          },
        ],
      },
      userList: [],
      classifyList: [],
      patientItem: { researchLibrariesId: null },
      picMarkDialogVisible: false,
      currentUrl: "",
      imgList: [],
      myImgIndex: "", //picData 第几组的index下 第几个照片的index
      uploadPhotoDialogVisible: false,
    };
  },
  watch: {},
  created() {
    this.getclassList();
    this.getuserList();
    this.getDeptTree();
    this.getLibraryList();
    this.getdeptNameList();
  },
  mounted() {
    // this.getAnnotateList();
  },
  computed: {
    ...mapGetters(["dept", "hospital", "device"]),
    isAdmin() {
      return this.$store.state.user.name === "admin" ? true : false;
    },
  },
  methods: {
    isHaveEditPermission(row) {
      if (this.isAdmin) {
        return false;
      } else {
       // console.log(row.createBy != this.nickName);
        return row.createBy != this.nickName;
      }
    },
    isHaveOperationPermission(row) {
      if (this.isAdmin) {
        return false;
      } else {
        return false;//!row.nickNames.includes(this.nickName);
      }
    },
    addLibraryPindex(data) {
      const Mdata = {
        researchLibrariesId: this.libraryId,
        sysResearchLibrariesPhotoList: data,
      };
      photoAddtoLibrary(Mdata).then((response) => {
        if (response.code == 200) {
          // this.photosLibraryDialogVisible = false;//张老师说这里库中选择照片，加入标注库后，选择的页面自动跳掉了，因为一次加很多张照片，页面跳掉使用就很不方便了
          this.getLibraryList();
          this.$modal.msgSuccess(response.msg);
        }
      });
    },
    oneClickJoinAllPhoto(data) {
      const Mdata = {
        researchLibrariesId: this.libraryId,
        params: data,
      };
      console.log("Mdata", Mdata);
      allPhotoAddtoLibrary(Mdata).then((response) => {
        if (response.code == 200) {
          this.getLibraryList();
          this.$modal.msgSuccess(response.msg);
        }
      });
    },
    // 回显医院及门诊
    getdeptNameList() {
      deptNameList().then((response) => {
        this.deptNameLists = response.data;
      });
    },
    refreshData(data) {
      this.libraryQueryParams.pageNum = 1;
      this.libraryQueryParams.hospitalId = data.hospitalId;
      this.libraryQueryParams.deptId = data.deptId;
      this.getLibraryList();
    },
    newAdd() {
      this.resetForm("submitLibraryForm");
      this.libraryId = 0;
      this.libraryTitle = "新增标注库";
      this.libraryDialogVisible = true;
    },
    btnEditLibrary(row) {
      getLibrary(row.researchLibrariesId).then((response) => {
        if (response.code == 200) {
          this.submitLibraryForm = response.data;
          this.submitLibraryForm.projectLeaders =
            this.submitLibraryForm.projectLeaders
              .split(",")
              .map((item) => Number(item));
          this.libraryId = row.researchLibrariesId;
          this.libraryTitle = "修改标注库";
          this.libraryDialogVisible = true;
        }
      });
    },
    btnDeleteLibrary(row) {
      this.$confirm("此操作将永久删除该标注库, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteLibrary(row.researchLibrariesId).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("删除成功");
              this.getLibraryList();
            }
          });
        })
        .catch((error) => {
          console.log(error);
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    btnListLibrary(row) {
      this.libraryId = row.researchLibrariesId;
      this.annotationListDialogVisible = true;
    },
    btnAddToLibrary(row) {
      this.libraryId = row.researchLibrariesId;
      this.photosLibraryDialogVisible = true;
    },
    btnOutAddToLibrary(row) {
      this.patientItem.researchLibrariesId = row.researchLibrariesId;
      /** 新增按钮操作 */
      this.uploadPhotoDialogVisible = true;
    },
    btnSubmitLibraryForm() {
      this.submitLibraryForm.projectLeaders =
        this.submitLibraryForm.projectLeaders.join(",");
      this.$refs["submitLibraryForm"].validate((valid) => {
        let deptOptionsArr = this.deptOptionsArr;
        if (valid) {
          let that = this;
          deptOptionsArr.forEach(function (ele) {
            console.log(ele.deptId);
            if (ele.deptId == that.submitLibraryForm.deptId) {
              if (
                that.getSplit(ele.ancestors).length != 2 &&
                that.getSplit(ele.ancestors).length != 1
              ) {
                that.submitLibraryForm.hospitalId = ele.parentId;
              } else {
                that.submitLibraryForm.hospitalId = ele.deptId;
              }
            }
          });
          if (this.libraryId == 0) {
            addlibrary(this.submitLibraryForm).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.libraryDialogVisible = false;
                this.getLibraryList();
              }
            });
          } else {
            updatelibrary(this.submitLibraryForm).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.libraryDialogVisible = false;
                this.getLibraryList();
              }
            });
          }
        }
      });
    },
    getSplit(str) {
      return str.split(",");
    },
    getLibraryList() {
      listLibrary(this.libraryQueryParams).then((response) => {
        if (response.code == 200) {
          this.annotateLibraryList = response.rows;
          this.libraryTotal = response.total;
        }
      });
    },
    resetLibraryQuery() {
      this.resetForm("libraryQueryForm");
      this.handleQuery();
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      listDept().then((response) => {
        let data = response.data;
        this.deptOptionsArr = data;
        if (this.getSplit(this.dept.ancestors).length == 3) {
          //3级用户
          data.push(this.hospital); //默认加一个上级医院
        }
        this.deptOptions = this.handleTree(data, "deptId")[0].children;
        if (this.deptOptions.length == 1) {
          this.baseInfo.deptId = this.deptOptions[0].deptId;
          if (this.deptOptions[0].parentId != 0) {
            this.baseInfo.hospitalId = this.deptOptions[0].parentId;
          }
        }
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    watchBigPic(row, Mindex) {
      console.log("---------+++++++", row, Mindex);
      this.myImgIndex = Mindex;
      this.currentUrl = row.rtList[Mindex].photoAddress;
      row.rtList.forEach((item) => {
        item.patientName = row.patientName;
        item.age = row.age;
        item.doctorDiagnosis = row.diagnosis.replace(/ *\([^)]*\) */g, "");
      });
      this.imgList = row.rtList;
      this.picMarkDialogVisible = true;
    },
    /** 查询咨询医生 */
    getuserList() {
      listUser({ pageNum: 1, pageSize: 9999, roleId: "" }).then((res) => {
        this.userList = res.rows;
      });
    },
    changeColorValue(e) {
      console.log(e);
    },

    // 获取专病列表
    getclassList() {
      this.loading = true;
      let params = {
        pageNum: 1,
        pageSize: 9999,
        status: "0",
      };
      listClassify(params).then((response) => {
        this.loading = false;
        this.sysManageDiseases = response.rows;
      });
    },

    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    /** 查询标注列表 */
    getAnnotateList() {
      listAnnotate(this.queryParams).then((res) => {
        console.log(res);
        this.annotateList = res.rows.map((item) => {
          return {
            ...item,
            annotateStateValue: this.sysUseTypeArr.find(
              (it) => it.value == item.annotateState
            )?.label,
          };
        });
        this.total = res.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        title: "", //文本标题
        type: "", //文本类别 （字典管理）
        diseaseIds: "", //专病类型 （字典管理）
        status: "0", //使用状态 //0在用
        content: "", //文本内容
        publisher: "", //创建人
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.libraryQueryParams.pageNum = 1;
      this.getLibraryList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.inputDisabled = false;
      this.open = true;
      this.title = "上传照片";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.inputDisabled = true;
      const textId = row.textId;
      getText(textId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑照片";
      });
    },
  },
};
</script>
<style scoped lang="scss">
.el-tag {
  margin-right: 15px;
}
.tooltipSlotBox {
  max-width: 460px;
  display: flex;
  flex-wrap: wrap;
  .img-txt {
    //display: flex;
    //flex-direction: column;
    //text-align: center;
    //margin: 14px;
    margin: 6px;

    .user-info-head {
      width: 72px;
      height: 104px;

      //border: 1px solid #000;
      .img-style {
        width: 100%;
        height: 100%;

        ::v-deep .el-image__error {
          opacity: 0;
        }
      }
    }
  }
}
::v-deep .el-dialog:not(.is-fullscreen) {
  margin-top: 0 !important;
}
</style>
